package com.ticket.sass.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.mapper.CommoditySkuMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.CommoditySkuEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品SKU 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-06
 */
@Service
public class CommoditySkuServiceImpl extends ServiceImpl<CommoditySkuMapper, CommoditySkuEntity> implements BaseService<CommoditySkuEntity> {
    
    /**
     * 根据卖品ID查询对应的商品SKU列表
     * @param commodityId 卖品ID
     * @return 商品SKU列表
     */
    public List<CommoditySkuEntity> listByCommodityId(Long commodityId) {
        // 使用MyBatis-Plus的lambda查询
        return lambdaQuery().eq(CommoditySkuEntity::getCommodityId, commodityId).list();
    }
    
    /**
     * 根据卖品ID列表查询对应的商品SKU列表
     * @param commodityIds 卖品ID列表
     * @return 商品SKU列表的Map，以卖品ID为键，List<CommoditySkuEntity>为值
     */
    public Map<Long, List<CommoditySkuEntity>> mapByCommodityIds(List<Long> commodityIds) {
        if (commodityIds.size() == 0){
            return new HashMap<>();
        }
        
        // 使用MyBatis-Plus的lambda查询
        List<CommoditySkuEntity> skuList = lambdaQuery().in(CommoditySkuEntity::getCommodityId, commodityIds).list();
        
        // 构建Map，以卖品ID为键，List<CommoditySkuEntity>为值
        Map<Long, List<CommoditySkuEntity>> resultMap = new HashMap<>();
        for (Long commodityId : commodityIds) {
            List<CommoditySkuEntity> skuEntities = new ArrayList<>();
            for (CommoditySkuEntity skuEntity : skuList) {
                if (skuEntity.getCommodityId().equals(commodityId)) {
                    skuEntities.add(skuEntity);
                }
            }
            resultMap.put(commodityId, skuEntities);
        }
        
        return resultMap;
    }
    
    public Long countBy(List<Long> ids, Long commodityId){
        if (ids.isEmpty()){
            return 0L;
        }
        
        return this.count(new QueryWrapper<CommoditySkuEntity>().in("id", ids).eq("commodity_id", commodityId));
    }
}
